package com.xpp.yanbi.bimq;

import com.rabbitmq.client.Channel;
import com.xpp.yanbi.common.ErrorCode;
import com.xpp.yanbi.exception.BusinessException;
import com.xpp.yanbi.manager.MoonshotAiService;
import com.xpp.yanbi.model.enity.Chart;
import com.xpp.yanbi.service.ChartService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class BiMessageConsumer {
    @Resource
    private ChartService chartService;

    @Resource
    private MoonshotAiService moonshotAiService;


    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}",message);
        if (StringUtils.isBlank(message)){
            // 如果消息为空,拒绝当前消息，让消息重新入队
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart == null){
            // 如果图表为空,拒绝当前消息
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"图表为空");
        }
        // 先修改图表 状态为 "执行中"
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean result = chartService.updateById(updateChart);
        if (!result) {
            handleChartUpdateError(chart.getId(),"更新图表执行中状态失败");
            return;
        }
        // ai处理
        String aiContent = moonshotAiService.doChat(buildUserInput(chart));
        String[] splits = aiContent.split("【【【【【【【");
        if (splits.length < 3) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "ai 响应结果异常");
        }
        String genChart = splits[1];
        String genResult = splits[2];
        // 得到ai结果 再更新
        updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setGenChart(genChart);
        updateChart.setGenResult(genResult);
        updateChart.setStatus("succeed");
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            handleChartUpdateError(chart.getId(),"更新图表成功状态失败");
        }
    }

    /**
     * 构建用户输入
     * @param chart 图表对象
     * @return 用户输入字符串
     */
    private String buildUserInput(Chart chart) {
        // 获取图表的目标、类型和数据
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        // 拼接分析目标
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvData).append("\n");
        // 将StringBuilder转换为String并返回
        return userInput.toString();
    }


    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus("failed");
        chart.setExecMessage(execMessage);
        boolean result = chartService.updateById(chart);
        if (!result) {
            log.error("更新图表状态失败," + chartId + ", " + execMessage);
        }
    }
}
